package com.hdy.oa.web.action.department;

import com.hdy.DBUtils.JDBC;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;


@WebServlet("/dept/add")
public class DepAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String deptNo = request.getParameter("deptNo");
        String dept = request.getParameter("dept");
        String loc = request.getParameter("loc");

        Connection connection=null;
        PreparedStatement ps=null;
        int count=0;

        try {
            connection=JDBC.getConnection();
            String sql="insert into dept(DEPTNO,DNAME,LOC) values (?,?,?);";
            ps=connection.prepareStatement(sql);
            ps.setString(1,deptNo);
            ps.setString(2,dept);
            ps.setString(3,loc);
            count=ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps,null);
        }
        String contextPath = request.getContextPath();
        if(count==1){
            // request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(contextPath+"/dept/list");
        }else{
            //request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(contextPath+"/error.html");
        }
    }
}
